package touro.mancala.master;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

import touro.mancala.core.Constants;
import touro.mancala.slave.Board;

public class ClientSocketHandler implements Runnable {

	private static final Logger logger = Logger.getLogger(ClientSocketHandler.class.getName());
	
	Socket socket;
	Server server;

	public ClientSocketHandler(Socket clientSocket, Server server) {
		socket = clientSocket;
		this.server = server;

	}

	@Override
	public void run() {

		InputStream in;
		BufferedReader reader;
		try {
			in = socket.getInputStream();
			reader = new BufferedReader(new InputStreamReader(in));
		} catch (IOException e1) {
			e1.printStackTrace();
			return;
		}

		while (true) {
			try {
				String line = reader.readLine();
				logger.log(Level.INFO, "Read line: " + line);

				StringTokenizer tokenizer = new StringTokenizer(line);
				String board = tokenizer.nextToken();
				String activePlayer = tokenizer.nextToken();

				Request request = new Request(socket, new Board(board,
						activePlayer, false));

				server.getRequestManager().addRequest(request);
			} catch (IOException e) {
				//e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}

}
